﻿@page "/search"
@page "/search/{query}"
@inherits BaseSearchPage

@using AcBlog.Client.UI.Pages.Posts.Components

<PageContainer Title="Search" PageTitle="@Title">
    <Breadcrumb>
        <Breadcrumb>
            <BreadcrumbItem>
                <a href="">
                    <MdiIcon Type="@IconNames.Home" />
                    <span>Home</span>
                </a>
            </BreadcrumbItem>
            <BreadcrumbItem>
                <span>
                    <MdiIcon Type="@IconNames.Search" />
                    <span>Search</span>
                </span>
            </BreadcrumbItem>
        </Breadcrumb>
    </Breadcrumb>
    <Content>
        <Search Placeholder="Search" Size="@InputSize.Large" OnSearch="@OnSearch" OnPressEnter="@OnSearch" @bind-Value="@CurrentQuery" />
    </Content>

    <ChildContent>
        <Loader OnLoad="@OnLoad" @ref="loader">
            <PagingList Data="@Data" Column="1" OnUpdatePage="@OnUpdatePage" OnPageTo="@OnPageTo">
                <ItemTemplate>
                    <PostListItem Id="@context" ShowType="true"></PostListItem>
                </ItemTemplate>
            </PagingList>
        </Loader>
    </ChildContent>
</PageContainer>

@code {
    [Parameter]
    public string Query { get; set; } = null;

    string CurrentQuery { get; set; } = "";

    const int PageSize = 10;

    PagingData<string> Data { get; set; }

    int PageNumber { get; set; } = 0;

    private Loader loader;

    private async Task OnLoad()
    {
        if (string.IsNullOrWhiteSpace(CurrentQuery))
        {
            Title = "";
            Data = new PagingData<string>(Array.Empty<string>());
        }
        else
        {
            Title = "Loading...";
            Data = await Service.PostService.QueryPaging(new PostQueryRequest
            {
                Term = CurrentQuery,
                Pagination = new Data.Models.Actions.Pagination
                {
                    CurrentPage = PageNumber,
                    PageSize = PageSize
                }
            });
            Title = $"Page {Data.CurrentPage.CurrentPage + 1}";
        }
    }

    private async Task OnPageTo(int pageNumber)
    {
        PageNumber = pageNumber;
        await OnUpdatePage();
    }

    private async Task OnUpdatePage() => await loader.Load();

    private async Task OnSearch()
    {
        if (string.IsNullOrWhiteSpace(CurrentQuery))
            return;
        PageNumber = 0;
        NavigationManager.NavigateTo(UrlGenerator.Search(CurrentQuery));
        await loader.Load();
    }

    protected override void OnParametersSet()
    {
        CurrentQuery = Query ?? "";
        base.OnParametersSet();
    }
}
